package com.fingard.dsp.bank.directbank.cncbi01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ICurrTransPeriod;
import com.fingard.dsp.bank.reqrespobj.currtransperiod.Req4005;
import com.fingard.dsp.bank.reqrespobj.currtransperiod.Req4006;
import com.fingard.dsp.bank.reqrespobj.currtransperiod.RetAtsCurrTransPer;
import com.fingard.dsp.bank.reqrespobj.currtransperiod.detail.RetAtsCurrTransPerDetail;
import com.fingard.net.ConnState;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/11/19.
 */
public class CNCBI01CurrTransPeriod extends CNCBI01Base implements ICurrTransPeriod {
    @Override
    public RetAtsCurrTransPer currTransPeriod(Req4005 p_req4005) throws Exception {
        RetAtsCurrTransPer retAts = new RetAtsCurrTransPer(p_req4005.reqHeader);
        RetAtsCurrTransPerDetail detail = new RetAtsCurrTransPerDetail();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"GBK\"?>");
            XElement stream = new XElement("stream", "");
            stream.addChild(new XElement("action", "DLFIXSUB"));
            stream.addChild(new XElement("userName", bankFront.loginName));
//        <clientID></clientID><!--客户流水号 char(20)--
            stream.addChild(new XElement("clientID", p_req4005.singleDetail.askNumber));
//            <accountNo></accountNo><!--活期账号 char(19)-->
            stream.addChild(new XElement("accountNo", p_req4005.singleDetail.payAct));
//            <perd></perd><!--存期char(3) M03：三个月；M06：六个月；Y01：一年-->
            int month = DateHelper.getDifferMonths(Format.Date8Format.parse(p_req4005.singleDetail.beginDate),
                    Format.Date8Format.parse(p_req4005.singleDetail.endDate));
            if (month == 3) {
                stream.addChild(new XElement("perd", "M03"));
            } else if (month == 6) {
                stream.addChild(new XElement("perd", "M06"));
            } else if (month == 12) {
                stream.addChild(new XElement("perd", "Y01"));
            } else {
                stream.addChild(new XElement("perd", ""));
                //throw new Exception("存期只能是3个月，半年或者一年");
            }
//            <memo></memo><!--备注 varchar(60)，可空-->
            stream.addChild(new XElement("memo", p_req4005.singleDetail.usage));
//            <tranAmt></tranAmt><!--交易金额 decimal（15，2）-->
            stream.addChild(new XElement("tranAmt", p_req4005.singleDetail.payAmount));
            //当前付方账户一定是香港账户
//            <wdtp></wdtp><!--结转方式 char(1)，0：自动结转；1：不自动结转；当活期账号为中信银行（国际）-香港账户时，结转方式取值为：A: 本金及利息自动转结、O: 本金及利息保留在定期帐户，允许手动转存-->
            if ("0".equals(p_req4005.singleDetail.autoFlag)) {
                stream.addChild(new XElement("wdtp", "O"));
            } else {
                stream.addChild(new XElement("wdtp", "A"));
            }
//            <cryType></cryType><!--币种 char(2), 活期账号为中信银行（国际）-香港账户时，必输；付款账号非中信银行（国际）-香港账户时，不需上送该字段-->
            stream.addChild(new XElement("cryType", convertCurToBank(p_req4005.singleDetail.currencyID)));
//            <sDate></sDate><!--起始日期char(8), 活期账号为中信银行（国际）-香港账户时必输; 付款账号非中信银行（国际）-香港账户时，不需上送该字段；格式: YYYYMMDD -->
            stream.addChild(new XElement("sDate", p_req4005.singleDetail.beginDate.replace("-", "")));
//            <mDate></mDate><!--到期日char(8), 活期账号为中信银行（国际）-香港账户时，必输；付款账号非中信银行（国际）-香港账户时，不需上送该字段；格式: YYYYMMDD -->
            stream.addChild(new XElement("mDate", p_req4005.singleDetail.endDate.replace("-", "")));
//            <rate></rate><!--利率 decimal（18,8），活期账号为中信银行（国际）-香港账户时，选输；活期账号非中信银行（国际）-香港账户时，不需上送该字段-->
            stream.addChild(new XElement("rate", p_req4005.singleDetail.rate));
            xmlWriter.writeEndDocument();
            nodeAnalysis(p_req4005.singleDetail.srcXElement, stream, getCharset());
            xmlWriter.writeXElement(stream);
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpBkMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpBkMsg);
                if (tmpBkReader != null) {
                    detail.respCode = "0";
                    detail.respInfo = tmpBkReader.getFirstText("/stream/statusText");
                    detail.transState = tmpBkReader.getFirstText("/stream/status");
                    detail.payInfoCode = detail.transState;
                    detail.reqSeqID = p_req4005.singleDetail.askNumber;
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpBkMsg.toString();
                }
            } else if (bankResult[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = bankResult[1];
                detail.reqSeqID = p_req4005.singleDetail.askNumber;
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = bankResult[0];
            } else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }

    @Override
    public RetAtsCurrTransPer qryCurrTransPeriod(Req4006 p_req4006) throws Exception {
        RetAtsCurrTransPer retAts = new RetAtsCurrTransPer(p_req4006.reqHeader);
        RetAtsCurrTransPerDetail detail = new RetAtsCurrTransPerDetail();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CNCBI01Header header = new CNCBI01Header();
            header.action = "DLCIDSTT";
            writeCommonHeader(xmlWriter, header);
//            <clientID></clientID><!--客户流水号char(20)-->
            xmlWriter.writeElementString("clientID", p_req4006.askNumber);
//            <type></type><!--
            xmlWriter.writeElementString("type", "");
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpBkMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpBkMsg);
                if (tmpBkReader != null) {
                    String tmpStatus = tmpBkReader.getFirstText("/stream/status");
                    String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
                    if (tmpStatus != null && tmpStatus.equals("AAAAAAA")) {
                        if (tmpBkReader.read("/stream/list")) {
                            if (tmpBkReader.readedXElement.getAttrValue("name").equals("userDataList")) {
                                detail.reqSeqID = p_req4006.askNumber;
                                detail.respCode = "0";
                                detail.respInfo = tmpBkReader.readedXElement.getSingleText("row/statusText");
                                detail.payInfoCode = tmpBkReader.readedXElement.getSingleText("row/status");
                                detail.transState = "stt+" + tmpBkReader.readedXElement.getSingleText("row/stt");
                                if ("AAAAAAB".equals(detail.payInfoCode) || "AAAAAAC".equals(detail.payInfoCode)) {
                                    detail.transState = detail.payInfoCode;
                                }
                            } else {
                                detail.respCode = "-1";
                                detail.respInfo = "未找到userDataList的list";
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = "未找到/stream/list";
                        }
                    } else if (tmpStatus != null && tmpStatus.length() > 0) {
                        if ("ED12001".equals(tmpStatus) || "ED12002".equals(tmpStatus)) {//系统登录中,请稍候再试.
                            detail.respCode = "-1";
                        } else {
                            detail.respCode = "0";
                        }
                        detail.reqSeqID = p_req4006.askNumber;
                        detail.payInfoCode = tmpStatus;
                        detail.respInfo = tmpStatusText;
                        detail.transState = tmpStatus + "+" + tmpStatusText;
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpStatusText;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpBkMsg.toString();
                }
            } else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }
}
